//
//  ASTextMainVC.m
//  AvatarShow
//
//  Created by xunruiIOS on 2021/4/29.
//

#import "ASTextMainVC.h"
#import "ASNoneView.h"
#import "ASTextHeadView.h"
#import "ASTextMainCell.h"
#import "ASHomeApi.h"
#import "MJRefreshNormalHeader.h"
#import "MJRefreshAutoNormalFooter.h"

@interface ASTextMainVC () <UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *dataArr;
@property (assign, nonatomic) NSInteger page;
@property (strong, nonatomic) ASNoneView *noneView;
@property (strong, nonatomic) ASTextHeadView *headView;
@property (strong, nonatomic) NSString *searchContent;
@property (strong, nonatomic) NSMutableArray *tagArr;
@property (strong, nonatomic) ASTextModel *selectModel;         ///选择标签
@property (strong, nonatomic) NSArray *colorArr;

@end

@implementation ASTextMainVC

- (void)dealloc{
    FELog(@"ASTextMainVC页面释放");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个性文案";
    self.view.backgroundColor = BACKGROUND_COLOR;
    self.colorArr = @[@"#FFF0D9",@"#DDE2FB",@"#FEDFDD",@"#D9F5E6",@"#EBD9F5",@"#FFE8D8",@"#DDF1FF",];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    [self loadClassTagData];
    // Do any additional setup after loading the view.
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.backgroundColor = self.view.backgroundColor;
        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        [_tableView registerClass:[ASTextMainCell class] forCellReuseIdentifier:ASTextMainCellStr];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ASTableCellNoneStr"];
        [_tableView registerClass:[ASTextHeadView class] forHeaderFooterViewReuseIdentifier:ASTextHeadViewStr];
     
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(firstLoadData:)];
        header.lastUpdatedTimeLabel.hidden = YES;
        _tableView.mj_header = header;
        
        MJRefreshAutoNormalFooter *foot = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        [foot endRefreshingWithNoMoreData];
        [foot setTitle:@"" forState:MJRefreshStateNoMoreData];
        _tableView.mj_footer = foot;
    }
    return _tableView;
}

- (ASNoneView *)noneView{
    if (!_noneView) {
        _noneView = [[ASNoneView alloc]initWithFrame:CGRectZero];
        [_noneView.logoImage setImage:[UIImage imageNamed:@"me_wsj"]];
        _noneView.titleLab.text = @"暂时没有相关数据";
    }
    return _noneView;
}

#pragma mark - LoadData
- (void)firstLoadData:(BOOL)ifHUD{
    self.page = 1;
    [self.tableView setContentOffset:CGPointMake(0, -Height_NavBar)];
    if ([self.searchContent isNotBlank]) {
        [self loadSearchData:ifHUD];
    }else{
        [self loadMainData:ifHUD];
    }
}

- (void)loadMoreData{
    self.page ++;
    if ([self.searchContent isNotBlank]) {
        [self loadSearchData:NO];
    }else{
        [self loadMainData:NO];
    }
}

///加载顶部标签数据
- (void)loadClassTagData{
    [MBProgressHUD showMessage:@"加载中..."];
    [ASHomeApi loadTextTagDataCompletion:^(ASBaseModel *  _Nonnull result) {
        if (result.state.intValue == 1) {
            [self.tagArr removeAllObjects];
            self.tagArr = [NSMutableArray new];
            for (int x = 0; x < result.resultArr.count; x ++) {
                ASTextModel *model = result.resultArr[x];
                if (x == 0) {
                    model.ifSelect = YES;
                }
                if (self.colorArr.count > x) {
                    model.colorStr = self.colorArr[x];
                }else{
                    model.colorStr = self.colorArr[x-self.colorArr.count];
                }
                [self.tagArr addObject:model];
            }
            if (self.tagArr.count > 0) {
                self.selectModel = self.tagArr[0];
                [ASTool addUMTongJiKey:@"home" subKey:@"personality_copy" titleStr:@"创意个性"];
            }
            [self firstLoadData:NO];
        }else{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:result.errorMsg];
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:FENETERROR];
    }];
}

///加载主数据
- (void)loadMainData:(BOOL)ifHUD{
    if (ifHUD) {
        [MBProgressHUD showMessage:@"加载中..."];
    }
    [ASHomeApi loadTextListData:self.page classifyId:self.selectModel.tID Completion:^(ASBaseModel *  _Nonnull result) {
        [MBProgressHUD hideHUD];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if (result.state.intValue == 1) {
            if (self.page == 1) {
                [self.dataArr removeAllObjects];
                self.dataArr = [NSMutableArray new];
            }
            [self.dataArr addObjectsFromArray:result.resultArr];
            [self.tableView reloadData];
            if (!result.hasMore) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }else{
            [MBProgressHUD showError:result.errorMsg];
        }
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:FENETERROR];
    }];
}

///加载搜索数据
- (void)loadSearchData:(BOOL)ifHUD{
    if (ifHUD) {
        [MBProgressHUD showMessage:@"加载中..."];
    }
    [ASHomeApi loadTextSearchListData:self.page wordStr:self.searchContent Completion:^(ASBaseModel *  _Nonnull result) {
        [MBProgressHUD hideHUD];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if (result.state.intValue == 1) {
            if (self.page == 1) {
                [self.dataArr removeAllObjects];
                self.dataArr = [NSMutableArray new];
            }
            for (ASTextModel *subM in result.resultArr) {
                subM.colorStr = [self backgroundRandomColor];
                [self.dataArr addObject:subM];
            }
            [self.tableView reloadData];
            if (!result.hasMore) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }else{
            [MBProgressHUD showError:result.errorMsg];
        }
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:FENETERROR];
    }];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count>0?self.dataArr.count:1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.dataArr.count > 0){
        if (self.dataArr.count > indexPath.row) {
            ASTextModel *model = self.dataArr[indexPath.row];
            return model.mainH;
        }
        return 85;
    }
    return SCREENH_HEIGHT;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return [ASTextHeadView headHeightIfTag:self.searchContent];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    self.headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:ASTextHeadViewStr];
    self.headView.contentView.backgroundColor = self.view.backgroundColor;
    if (self.headView.tagView.dataArr.count < 1) {
        self.headView.tagView.dataArr = self.tagArr;
    }
    if ([self.searchContent isNotBlank]) {
        self.headView.tagView.hidden = YES;
    }else{
        self.headView.tagView.hidden = NO;
    }
    @weakify(self);
    self.headView.searchView.clickSearchBlock = ^(NSString * _Nonnull searchContent) {
        @strongify(self);
        [ASTool addUMTongJiKey:@"home" subKey:@"personality_copy" titleStr:@"搜索"];
        self.searchContent = searchContent;
        [self firstLoadData:YES];
    };

    self.headView.tagView.clickSubIndexBlock = ^(NSInteger selectIndex) {
        @strongify(self);
        if (self.tagArr.count > selectIndex) {
            ASTextModel *subModel = self.tagArr[selectIndex];
            [ASTool addUMTongJiKey:@"home" subKey:@"personality_copy" titleStr:subModel.name];
            self.selectModel = subModel;
            [self firstLoadData:YES];
        }
    };
    
    return self.headView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.dataArr.count > 0){
        ASTextMainCell *cell = [tableView dequeueReusableCellWithIdentifier:ASTextMainCellStr];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (self.dataArr.count > indexPath.row) {
            ASTextModel *model = self.dataArr[indexPath.row];
            cell.mainLab.text = model.content;
            if ([self.searchContent isNotBlank]) {
                [cell.mainView setBackgroundColor:[UIColor colorWithHexString:model.colorStr]];
            }else{
                [cell.mainView setBackgroundColor:[UIColor colorWithHexString:self.selectModel.colorStr]];
            }
        }
        return cell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ASTableCellNoneStr"];
        for (UIView *subV in cell.contentView.subviews) {
            if ([subV isKindOfClass:[ASNoneView class]]) {
                [subV removeFromSuperview];
            }
        }
        [cell.contentView addSubview:self.noneView];
        [self.noneView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.dataArr.count > indexPath.row) {
        ASTextModel *model = self.dataArr[indexPath.row];
        UIPasteboard *pab = [UIPasteboard generalPasteboard];
        pab.string = model.content;
        if (pab == nil) {
            [MBProgressHUD showError:@"复制失败"];
        } else {
            [MBProgressHUD showSuccess:@"复制成功"];
        }
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    cell.backgroundColor = [UIColor colorWithHexString:@"ffffff"];
}


//数组中的随机色值
- (NSString *)backgroundRandomColor{
    int value = arc4random() % self.colorArr.count;
    return [self.colorArr objectAtIndex:value];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
